package com.elastic.mapping;

import com.elastic.util.User;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.delete.DeleteMappingRequestBuilder;
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse;
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse.FieldMappingMetaData;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.compress.CompressedString;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import java.util.concurrent.ExecutionException;
/**
 * 创建文件数据库和有数据类型的表
 * 
 * mapping 只能添加字段，不能修改字段类型。
 * @author xiaocai
 *
 */
public class createIndexWithMapping {
	public static String indexName="xiaocai";
	public static String indexName_sort_by="xiaocaisortby";
	public static String tableArr[]= {"user","storetable"};
	
	/**
	* 创建索引名称
	* @param indices 索引名称
	*/
	public  static void createIndex(String indices){
		ClientFactory.getInstance().admin().indices().prepareCreate(indices).execute().actionGet();
	}
	
	/**
	 * 转换成json对象 json=={"id":"1","name":"aa","age":"20"}
	 * 
	 * @param user
	 * @return
	 */
	private static String generateJson(User user) {
		String json = "";
		try {
			XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
					.startObject();
			contentBuilder.field("id", user.getId() + "");
			contentBuilder.field("name", user.getName());
			contentBuilder.field("age", user.getAge() + "");
			json = contentBuilder.endObject().string();
			System.out.println("json==" + json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return json;
	}

	
	/**创建索引带有文档数据的
	 * index
	 */
	public static void createIndex(Client client) {
		for (int i = 0; i < 10; i++) {
			User user = new User();
			user.setId(new Long(i));
			user.setName("huang fox:" + i);
			user.setAge(i % 100);
			IndexResponse response = client.prepareIndex("xiaocai", "user")
					.setSource(generateJson(user)).execute().actionGet();
			System.out.println(response.getIndex());
		}
	}

	/**
	* 创建mapping(feid("indexAnalyzer","ik")该字段分词IK索引 ；
	* feid("searchAnalyzer","ik")该字段分词ik查询；具体分词插件请看IK分词插件说明)
	* @param indices 索引名称； 数据库
	* @param mappingType 索引类型 表名
	* @throws Exception
	* 默认分词索引，： not_analyzed
	* store no : 需要高亮设置
	* {
	*   user:{propertys:{}}
	* 
	* }
	* 默认不分析也能搜的到
	*/
	public static void createMapping(String indices,String mappingType)throws Exception{
		XContentBuilder builder=XContentFactory.jsonBuilder()
		.startObject()
		.startObject(mappingType)//表的名字
		.startObject("properties")
		 .startObject("id").field("type","integer").field("store", "yes").endObject()
		//如果not_analyzed 默认是当做分词搜索的，完整的词就搜索不到结果了。
		.startObject("kw").field("type","string").field("store", "no").field("index", "not_analyzed").endObject()
		.startObject("edate").field("type", "long").endObject()
		// v10 会变成long 类型 ? 这是为什么。。。。。。。
		//.startObject("edate").field("type", "date").field("store","yes").field("format", "yyyy-MM-dd HH:mm:ss.SSS").endObject()
		//.startObject("edate").field("type","date")/*.field("format", "dateOptionalTime")*/.endObject()
		.endObject()
		.endObject()
		.endObject();
		System.out.println(builder.toString());
		PutMappingRequest mapping = Requests.putMappingRequest(indices).type(mappingType).source(builder);
		ClientFactory.getInstance().admin().indices().putMapping(mapping).actionGet();
	}

	//把table2的mapping
	public static void createTableMapping(String indices,String mappingType)throws Exception{
		XContentBuilder builder=XContentFactory.jsonBuilder()
				.startObject()
				.startObject(mappingType)//表的名字
				.startObject("properties")
				.startObject("id").field("type", "long").endObject()
						//如果not_analyzed 默认是当做分词搜索的，完整的词就搜索不到结果了。
				.startObject("kw").field("type", "string").field("store", "no").field("index", "not_analyzed").endObject()
				.startObject("edate").field("type","long").endObject()
						// v10 会变成long 类型 ? 这是为什么。。。。。。。
						//.startObject("edate").field("type", "date").field("store","yes").field("format", "yyyy-MM-dd HH:mm:ss.SSS").endObject()
						//.startObject("edate").field("type","date")/*.field("format", "dateOptionalTime")*/.endObject()
				.endObject()
				.endObject()
				.endObject();
		System.out.println(builder.toString());
		PutMappingRequest mapping = Requests.putMappingRequest(indices).type(mappingType).source(builder);
		ClientFactory.getInstance().admin().indices().putMapping(mapping).actionGet();
	}


	public static void updateMapping(String indices,String mappingType)throws Exception{
		XContentBuilder builder=XContentFactory.jsonBuilder()
				.startObject()
				.startObject(mappingType)//表的名字
				.startObject("properties")
				.startObject("id").field("type", "long").endObject()
						//如果not_analyzed 默认是当做分词搜索的，完整的词就搜索不到结果了。
				.startObject("kw").field("type", "string").field("store", "no").field("index", "not_analyzed").endObject()
				.startObject("kw2").field("type","long").field("store", "no").field("index", "not_analyzed").endObject()
				.startObject("edate").field("type","long").endObject()
						// v10 会变成long 类型 ? 这是为什么。。。。。。。
						//.startObject("edate").field("type", "date").field("store","yes").field("format", "yyyy-MM-dd HH:mm:ss.SSS").endObject()
						//.startObject("edate").field("type","date")/*.field("format", "dateOptionalTime")*/.endObject()
				.endObject()
				.endObject()
				.endObject();
		System.out.println(builder.toString());
		PutMappingRequest mapping = Requests.putMappingRequest(indices).type(mappingType).source(builder);
		ClientFactory.getInstance().admin().indices().putMapping(mapping).actionGet();
	}


	public static boolean  existfiledofMapping(final String indices,final String mappingType)throws Exception{
//		s
//		a.indices(indices).types(mappingType).fields("id","kw");
//		//ClientFactory.getInstance().admin().indices().getFieldMappings(request, null);
//		ClientFactory.getInstance().admin().indices().getFieldMappings(a, new ActionListener<GetFieldMappingsResponse>() {
//			public void onResponse(GetFieldMappingsResponse response) {
//				  FieldMappingMetaData  m = response.fieldMappings(indices, mappingType, "kw");
//				  System.out.println(m.fullName());
//			}
//			public void onFailure(Throwable e) {
//				
//			}
//		});
		
	   GetFieldMappingsResponse response = ClientFactory.getInstance().admin().indices().prepareGetFieldMappings(indices).setTypes(mappingType).get();
	   FieldMappingMetaData  m = response.fieldMappings(indices, mappingType, "kw");
	   if(m!=null){
		   return true;
	   }
	   return false;
	
	}
	
	public static void fun3(String indices, String mappingType,String fileds){
		  ClusterState cs = ClientFactory.getInstance().admin().cluster().prepareState()  
	               .execute().actionGet().getState();  
	       IndexMetaData imd = cs.getMetaData()  
	               //这个名称同上面的名称  
	               .index(indices);  
	       //type的名称  
	       MappingMetaData mdd = imd.mapping(mappingType);
	       System.out.println(mdd != null);
	       //System.out.println(mdd.source().toString().indexOf(fileds)>-1);  
	}
	
	
	public static  void fun2(final String indices,final String mappingType){
//		GetFieldMappingsResponse response = ClientFactory.getInstance().admin().indices().prepareGetMappings(indices).setTypes(mappingType).
//		
//		GetMappingsRequestBuilder builder = ClientFactory.getInstance().admin().indices().prepareGetMappings(indices).setTypes(mappingType);
//		GetFieldMappingsResponse response = ClientFactory.getInstance().admin().indices().prepareGetFieldMappings(indices).setTypes(mappingType).execute().actionGet();
		
		//ClientFactory.getInstance().admin().indices().prepareStatus(indices).get().get
		  ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> ss = ClientFactory.getInstance().admin().indices().prepareGetMappings(indices).setTypes(mappingType).get().getMappings();
          System.out.println("sd");
           
          ImmutableOpenMap<String, MappingMetaData> mm= ss.get(indices);
          MappingMetaData data = mm.get(mappingType);
		try {
			CompressedString st = data.source();
			System.out.println(st);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
          //System.out.println("ff:"+f.get("id"));
          //ObjectContainer<ImmutableOpenMap<String, MappingMetaData>> tt = ss.values();
        
          
		 
		 //		ImmutableOpenMap<String, MappingMetaData> mappings =  ClientFactory.getInstance().admin().cluster().prepareState().execute().actionGet().getState().getMetaData().getIndices().get("itest").getMappings();
//	System.out.println(mappings.get("news").source());
//		
//		
//		System.out.println(mappings.get(tableArr[1]).);
//		
//		 mappings.keys();
		 
		 //ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> ss = ClientFactory.getInstance().admin().indices().prepareGetFieldMappings(indices).setTypes(mappingType).get().mappings();
	
	
	}
	
   
   public static void createHomeBusinessMapping(String table, String indexName) throws Exception{
       //创建
       XContentBuilder mapping = XContentFactory.jsonBuilder()
               .startObject()
               .startObject(table)
               .startObject("properties")
               .startObject("homeBusinessId").field("type", "string").field("index", "not_analyzed").endObject()
               .startObject("empUuid").field("type", "string").field("index", "not_analyzed").endObject()
               .startObject("businessType").field("type", "string").field("index", "not_analyzed").endObject()
               .endObject()
               .endObject()
               .endObject();
       PutMappingRequest mappingRequest = Requests.putMappingRequest(indexName)
               .type(table).source(mapping);
       ClientFactory.getInstance().admin().indices().putMapping(mappingRequest).actionGet();
   }
    
   /**
    * 判断type是否存在 删除表名
    * @param indexName
    * @param typeName
    * @return
    * @throws ExecutionException
    * @throws InterruptedException
    */
   public static boolean isTypeExists(String indexName, String typeName)
           throws InterruptedException, ExecutionException {
       TypesExistsResponse typeExist = ClientFactory.getInstance().admin()
               .indices().prepareTypesExists(indexName).setTypes(typeName).get();
       return typeExist.isExists();
   }

	public static boolean isIndexExists(String indexName) {
		IndicesExistsResponse indicesExistsReq =
				ClientFactory.getInstance().admin().indices().prepareExists(indexName).get();
		return indicesExistsReq.isExists();
	}

   /**
    * 删除数据结构
    * @param indexName
    * @param typeName
    * @return
    */
   public static boolean deleteMapping(String indexName, String typeName) {
       try {
    	   if(isTypeExists(indexName,typeName)){
    		   DeleteMappingRequestBuilder deleteMappingRequestBuilder = ClientFactory.getInstance().admin().indices().prepareDeleteMapping(indexName).setType(typeName);
               deleteMappingRequestBuilder.get();
    	   }
       } catch (Exception ex) {
           ex.printStackTrace();
       }
       return true;
   }
   
  

   //创建mapping 的时候，同时创立了表结构吗？ 但是没有数据。
   //删除mappinig，相当于把表删除了和数据也一起删除了。
   //创建mapping,如果存在这样的mapping,就修改，不存在就添加。
	public static void main(String[] args)throws Exception {
		createIndex(indexName);
//		
//	    createMapping(indexName, tableArr[1]);
//		deleteDevMapping("fxtweb_ruiyang3_dev", "property");
		
//		long start =System.currentTimeMillis();
//		fun3(indexName,tableArr[1],"id");
//	    //System.out.println(existfiledofMapping(indexName,tableArr[1]));
//	    long end =System.currentTimeMillis();
//	    System.out.println(end-start);
	    //deleteMapping(client,"xiaocai","storetable");
	}
}
